<?php
error_reporting(E_ALL);

/**
 * Context Class.
 * Singleton resource for
 * session and site information.
 *
 */

require_once 'helpers.inc';
require_once "UserClass.inc";

class Context
{
    private $_languages ;
    private $_pagealias ;

	function __construct($pagealias) {
        global $DpDb ;

        if( ! isset( $DpDb ) ) {
            require_once "DpDbClass.inc" ;
            $DpDb = new DpDb() ;
        }
		$this->_pagealias = $pagealias;
	}


    public function PageAlias() {
        return $this->_pagealias ;
    }


	public function InitUser() {
        global $User;
        global $DpDb;

        // Is there a session?
        $username = @$_SESSION['username'];
        if(! empty($username)) {
            if($username !== USER_ANONYMOUS) {
                $User = new User($username);
                return;
            }
            // should not have stored anonymous
            $sql = "DELETE FROM sessions
                    WHERE username = '".USER_ANONYMOUS."'";
            $DpDb->SqlExecute($sql);
        }

        // no session - password verification required
        $username = Arg("username");
        $password = Arg("password");
        if(empty($username) || empty($password)) {
            $this->SetUserAnonymous();
            return;
        }

        require_once "phpBB3.inc" ;
        $bb = new phpBB3( $username, $password ) ;

        if($password != "xxyyzzyyxx" && ! $bb->IsBbUser()) {
            $this->SetUserAnonymous();
            return ;
        }


        // die("abcde");
        // $passwordMD5 = MD5(Arg("password")) ;

        if($password == "xxyyzzyyxx" || $bb->IsValidPassword()) {
            $_SESSION['username'] = $username ;
            if( ! $this->IsDpUser( $username ) ) {
                $this->AddDpUser( $username ) ;
            }
            $User = new User($username);

        }
        else {
            $this->SetUserAnonymous() ;
        }

        return;
    }

    private function SetUserAnonymous() {
        unset($_SESSION['username']);
        $User = new User(USER_ANONYMOUS);
    }

    public function LogOut() {
        global $User ;
        $User->LogOut() ;
    }


    public function SaveSession() {
        ini_set('session.bug_compat_warn', 0 );
        session_write_close();
    }

	public function IsLoggedIn() {
		global $User;
		return isset($User) && $User->IsLoggedIn();
	}

    public function Profile() {
        global $User;
        assert(isset($User));
        return isset($User) ? $User->Profile() : null ;
    }

	public function ActiveUserCount() {
		static $icount;
		global $DpDb;
		if(!isset($icount)) {
			$icount = $DpDb->SqlOneValue("
                SELECT COUNT(DISTINCT username)
                FROM page_events
                WHERE timestamp >= UNIX_TIMESTAMP() - 60 * 60 * 24");
		}
		return $icount;
	}

	public function totalUserCount() {
		static $icount;
		global $DpDb;
		if(!isset($icount)) {
			$icount = $DpDb->SqlOneValue("
                SELECT COUNT(DISTINCT username)
                FROM page_events");
		}
		return $icount;
	}


	public function LogEvent( $projectid = null, 
                              $pagecode = null,
                              $version = 0,
                              $taskcode = null,
                              $eventcode = null ) {
		global $DpDb;
		global $User;

        $eventcode  = QuoteOrNull($eventcode);
        $username   = QuoteOrNull($User->UserName()) ;
        $projectid  = QuoteOrNull($projectid) ;
        $pagecode   = QuoteOrNull($pagecode) ;
        $taskcode   = QuoteOrNull($taskcode) ;
        $version    = "$version" ;

		$sql = "INSERT INTO eventlog
                (
                    eventcode,
                    createtime,
                    username,
                    projectid,
                    pagecode,
                    taskcode,
                    versionnumber 
                ) VALUES (
                    $eventcode,
                    UNIX_TIMESTAMP(),
                    $username,
                    $projectid,
                    $pagecode,
                    $taskcode,
                    $version
                )";
		$DpDb->SqlExecute($sql);
	}


	public function Locations() {
		return $this->_locations;
	}


    public function ScheduleTasks() {
        global $DpDb;
        $sql = "SELECT * FROM tasks
                WHERE isscheduled <> 0
                ORDER BY SequenceNumber";
        return $DpDb->SqlRows($sql);
    }


    public function Tasks() {
        global $DpDb;
        $sql = "SELECT * FROM tasks
                ORDER BY SequenceNumber";
        return $DpDb->SqlRows($sql);
    }


    public function Task($taskcode) {
        global $DpDb;
        $sql = "SELECT * FROM tasks
                WHERE taskcode = '$taskcode'
                ORDER BY SequenceNumber";
        return $DpDb->SqlOneObject($sql);
    }



    private function AddDpUser($username) {
        global $DpDb;
        $sql = "INSERT INTO users
                (
                    username,
                    date_created
                )
                VALUES
                (
                    '$username',
                    UNIX_TIMESTAMP()
                )";
        $DpDb->SqlExecute($sql);
    }


	public function NewProjectId() {
        global $DpDb;
        $str = date( "Ymd" ) ;
        $sql = "SELECT MAX(projectid) FROM projects
                WHERE projectid LIKE '$str%'";
        $max = $DpDb->SqlOneValue( $sql ) ;
        $i   = 1 + substr( $max, 8 ) ;
        $name = sprintf( "%s%03d", $str, $i ) ;
        return $name ;
	}
    

    private function IsDpUser( $username ) {
        global $DpDb ;
        $sql = "SELECT username FROM users
                WHERE username = '$username'";
        return $DpDb->SqlExists( $sql ) ;
    } 
    

    public function LanguageName($code) {
        global $iso_639;
        require_once "iso_639_list.inc" ;
        return empty( $iso_639[$code] ) ? "en" : $iso_639[$code]  ;
    }
}
?>
